<script lang="ts" setup>
import { Calendar, Delete, Edit, Message, QuestionFilled, Search, Plus } from "@element-plus/icons-vue";
import { reactive, ref, onMounted } from "vue";
import type { ComponentSize } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';

// -------------------- 分页相关状态 --------------------
// 多个分页组件的当前页码（可用于不同表格）
const currentPage1 = ref(1);
const currentPage2 = ref(1);
const currentPage3 = ref(1);
const currentPage4 = ref(1);
// 每页显示数量
const pageSize2 = ref(10);
const pageSize3 = ref(10);
const pageSize4 = ref(10);

// -------------------- 组件外观状态 --------------------
const size = ref<ComponentSize>('default');        // 组件尺寸（默认/小/中/大）
const background = ref(true);                     // 分页是否显示背景色
const disabled = ref(false);                      // 分页是否禁用

// -------------------- 表单数据模型 --------------------
const data = reactive({
  input: '',                  // 通用输入框内容
  searchQuery: ''             // 搜索关键词
});

// -------------------- 员工数据列表 --------------------
const tableData = ref([
  {
    id: 1,
    username: "jinyong",
    password: "123456",
    name: "金庸",
    gender: "男",
    image: "https://picsum.photos/200/200?random=1",
    job: "4",         // 职位编码（通过jobTypes映射为中文）
    entrydate: "2000-01-01", // 入职日期
    dept_id: 2,       // 部门编码（通过deptMap映射为中文）
    create_time: "2025-06-11 08:30:00", // 创建时间
    update_time: "2025-06-11 15:45:00"  // 更新时间
  },
  {
    id: 2,
    username: "zhangwuji",
    password: "123456",
    name: "张无忌",
    gender: "男",
    image: "https://picsum.photos/200/200?random=2",
    job: "2",
    entrydate: "2015-01-01",
    dept_id: 2,
    create_time: "2025-06-11 09:10:00",
    update_time: "2025-06-11 16:20:00"
  },
  {
    id: 3,
    username: "yangxiao",
    password: "123456",
    name: "杨逍",
    gender: "男",
    image: "https://picsum.photos/200/200?random=3",
    job: "2",
    entrydate: "2008-05-01",
    dept_id: 2,
    create_time: "2025-06-11 10:20:00",
    update_time: "2025-06-11 09:30:00"
  },
  {
    id: 4,
    username: "weiyixiao",
    password: "123456",
    name: "韦一笑",
    gender: "男",
    image: "https://picsum.photos/200/200?random=4",
    job: "2",
    entrydate: "2007-01-01",
    dept_id: 2,
    create_time: "2025-06-11 14:30:00",
    update_time: "2025-06-11 11:15:00"
  },
  {
    id: 5,
    username: "changyuchun",
    password: "123456",
    name: "常遇春",
    gender: "男",
    image: "https://picsum.photos/200/200?random=5",
    job: "2",
    entrydate: "2012-12-05",
    dept_id: 2,
    create_time: "2025-06-11 09:00:00",
    update_time: "2025-06-11 10:00:00"
  },
  {
    id: 6,
    username: "xiaozhao",
    password: "123456",
    name: "小昭",
    gender: "女",
    image: "https://picsum.photos/200/200?random=6",
    job: "3",
    entrydate: "2013-09-05",
    dept_id: 1,
    create_time: "2025-06-11 08:30:00",
    update_time: "2025-06-11 15:45:00"
  },
  {
    id: 7,
    username: "jixiaofu",
    password: "123456",
    name: "纪晓芙",
    gender: "女",
    image: "https://picsum.photos/200/200?random=7",
    job: "1",
    entrydate: "2005-08-01",
    dept_id: 1,
    create_time: "2025-06-11 09:10:00",
    update_time: "2025-06-11 16:20:00"
  },
  {
    id: 8,
    username: "zhouzhiruo",
    password: "123456",
    name: "周芷若",
    gender: "女",
    image: "https://picsum.photos/200/200?random=8",
    job: "1",
    entrydate: "2014-11-09",
    dept_id: 1,
    create_time: "2025-06-11 10:20:00",
    update_time: "2025-06-11 09:30:00"
  },
  {
    id: 9,
    username: "dingminjun",
    password: "123456",
    name: "丁敏君",
    gender: "女",
    image: "https://picsum.photos/200/200?random=9",
    job: "1",
    entrydate: "2011-03-11",
    dept_id: 1,
    create_time: "2025-06-11 14:30:00",
    update_time: "2025-06-11 11:15:00"
  },
  {
    id: 10,
    username: "zhaomin",
    password: "123456",
    name: "赵敏",
    gender: "女",
    image: "https://picsum.photos/200/200?random=10",
    job: "1",
    entrydate: "2013-09-05",
    dept_id: 1,
    create_time: "2025-06-11 09:00:00",
    update_time: "2025-06-11 10:00:00"
  },
  {
    id: 11,
    username: "luzhangke",
    password: "123456",
    name: "鹿杖客",
    gender: "男",
    image: "https://picsum.photos/200/200?random=11",
    job: "1",
    entrydate: "2007-02-01",
    dept_id: 1,
    create_time: "2025-06-11 08:30:00",
    update_time: "2025-06-11 15:45:00"
  },
  {
    id: 12,
    username: "hebiweng",
    password: "123456",
    name: "鹤笔翁",
    gender: "男",
    image: "https://picsum.photos/200/200?random=12",
    job: "1",
    entrydate: "2008-08-18",
    dept_id: 1,
    create_time: "2025-06-11 09:10:00",
    update_time: "2025-06-11 16:20:00"
  },
  {
    id: 13,
    username: "fangdongbai",
    password: "123456",
    name: "方东白",
    gender: "男",
    image: "https://picsum.photos/200/200?random=13",
    job: "2",
    entrydate: "2012-11-01",
    dept_id: 2,
    create_time: "2025-06-11 10:20:00",
    update_time: "2025-06-11 09:30:00"
  },
  {
    id: 14,
    username: "zhangsanfeng",
    password: "123456",
    name: "张三丰",
    gender: "男",
    image: "https://picsum.photos/200/200?random=14",
    job: "2",
    entrydate: "2002-08-01",
    dept_id: 2,
    create_time: "2025-06-11 14:30:00",
    update_time: "2025-06-11 11:15:00"
  },
  {
    id: 15,
    username: "yulianzhou",
    password: "123456",
    name: "俞莲舟",
    gender: "男",
    image: "https://picsum.photos/200/200?random=15",
    job: "2",
    entrydate: "2011-05-01",
    dept_id: 2,
    create_time: "2025-06-11 09:00:00",
    update_time: "2025-06-11 10:00:00"
  },
  {
    id: 16,
    username: "songyuanqiao",
    password: "123456",
    name: "宋远桥",
    gender: "男",
    image: "https://picsum.photos/200/200?random=16",
    job: "2",
    entrydate: "2010-01-01",
    dept_id: 2,
    create_time: "2025-06-11 08:30:00",
    update_time: "2025-06-11 15:45:00"
  },
  {
    id: 17,
    username: "chenyouliang",
    password: "123456",
    name: "陈友谅",
    gender: "男",
    image: "https://picsum.photos/200/200?random=17",
    job: "2",
    entrydate: "2015-03-21",
    dept_id: 2,
    create_time: "2025-06-11 09:10:00",
    update_time: "2025-06-11 16:20:00"
  }
]);

// -------------------- 工具函数 --------------------
// 日期格式化：将时间字符串转为中文格式（年月日 时分）
const formatDate = (dateString: string): string => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',    // 完整年份
    month: '2-digit',   // 两位月份
    day: '2-digit',     // 两位日期
    hour: '2-digit',    // 两位小时
    minute: '2-digit'   // 两位分钟
  });
};

// 职位编码映射表（数字转中文职位）
const jobTypes: Record<string, string> = {
  '1': '管理岗',
  '2': '技术岗',
  '3': '运营岗',
  '4': '高管'
};

// 部门编码映射表（数字转中文部门）
const deptMap: Record<number, string> = {
  1: '技术部',
  2: '运营部',
  3: '市场部'
};

// -------------------- 功能函数 --------------------
// 搜索员工
const handleSearch = () => {
  if (!data.searchQuery) {
    ElMessage.info('请输入搜索关键词');
    return;
  }

  // 多条件过滤：姓名、用户名、职位、部门
  const searchResults = tableData.value.filter(item =>
      item.name.includes(data.searchQuery) ||
      item.username.includes(data.searchQuery) ||
      jobTypes[item.job as string]?.includes(data.searchQuery) ||
      deptMap[item.dept_id as number]?.includes(data.searchQuery)
  );

  if (searchResults.length === 0) {
    ElMessage.warning('未找到匹配的记录');
  } else {
    tableData.value = searchResults;
    ElMessage.success(`找到 ${searchResults.length} 条记录`);
  }
};

// 重置搜索条件
const resetSearch = () => {
  data.searchQuery = '';
  ElMessage.info('搜索已重置');
};

// 编辑员工
const handleEdit = (row: any) => {
  ElMessage({
    type: 'info',
    message: `编辑员工: ${row.name}`,
    duration: 2000
  });
  console.log('编辑员工', row);
};

// 删除员工（带确认对话框）
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
      `确认删除员工 ${row.name} 吗？此操作不可恢复。`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    tableData.value = tableData.value.filter(item => item.id !== row.id);
    ElMessage.success('删除成功');
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 新增员工
const handleAddUser = () => {
  ElMessage({
    type: 'info',
    message: '新增员工功能',
    duration: 2000
  });
  console.log('新增员工');
};

// 页面加载完成后执行
onMounted(() => {
  ElMessage({
    type: 'success',
    message: '员工管理系统已加载完成',
    duration: 3000
  });
});
</script>

<template>
  <div class="app-container">
    <!-- 头部区域：标题和操作按钮 -->
    <header class="app-header">
      <h1 class="app-title">员工管理系统</h1>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddUser">
          <el-icon><Plus /></el-icon>新增员工
        </el-button>
      </div>
    </header>

    <!-- 主内容区域 -->
    <main class="app-main">
      <!-- 表格区域 -->
      <el-card class="table-card" shadow="always">
        <template #header>
          <div class="card-header">
            <el-icon><Calendar /></el-icon>
            <span>员工数据表格</span>
          </div>
        </template>
        <div class="table-search">
          <el-input
              v-model="data.searchQuery"
              placeholder="搜索用户名、姓名或职位"
              :prefix-icon="Search"
              class="search-input"
              @keyup.enter="handleSearch"
          />
          <el-button type="primary" class="search-button" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button class="reset-button" @click="resetSearch">
            重置
          </el-button>
        </div>
        <el-table :data="tableData" style="width: 100%" stripe hover>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="name" label="姓名" width="100" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="scope">
              <el-tag :type="scope.row.gender === '男' ? 'primary' : 'success'">
                {{ scope.row.gender }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="image" label="头像" width="100">
            <template #default="scope">
              <img :src="scope.row.image" alt="头像" class="user-avatar" />
            </template>
          </el-table-column>
          <el-table-column prop="job" label="职位" width="120">
            <template #default="scope">
              {{ jobTypes[scope.row.job] || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="entrydate" label="入职日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.entrydate) }}
            </template>
          </el-table-column>
          <el-table-column prop="dept_id" label="部门" width="120">
            <template #default="scope">
              {{ deptMap[scope.row.dept_id] || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="update_time" label="更新时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.update_time) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(scope.row)"
                  class="table-action-btn"
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  class="table-action-btn"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage4"
            v-model:page-size="pageSize4"
            :page-sizes="[10, 20, 50, 100]"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length"
        />
      </div>
    </main>
  </div>
</template>

<style scoped>
.app-container {
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
}

.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.app-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.app-main {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-search {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.search-input {
  width: 300px;
}

.reset-button {
  margin-left: auto;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 按钮对齐优化 */
.el-button--mini {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  padding: 2px 8px;
}

.el-button--mini .el-icon {
  margin-right: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-title {
    font-size: 20px;
  }

  .table-search {
    flex-direction: column;
    gap: 10px;
  }

  .search-input {
    width: 100%;
  }

  .reset-button {
    margin-left: 0;
  }
}
</style>